import React,{useState,useEffect,useRef} from 'react';
import { PageHeader, Steps, Button, Form,Input,Select,message,notification } from 'antd'
import './newsAdd.scss'
import axios from 'axios'
import NewsEditor from '../../../components/news-manage/NewsEditor'
const { Step } = Steps
const { Option } = Select

const Newsadd = (props) => {
  const newsForm = useRef(null)
  const [categoryList,setcategoryList] = useState([])
  const [numCurrent, setnumCurrent] = useState(0)
  const [FormConter, setFormConter] = useState({})
  const [TextEditor,setTextEditor] = useState('')
  const nextStep = () => {
    if (numCurrent === 0) {
      newsForm.current.validateFields().then(res => {
        setFormConter(res)
         setnumCurrent(numCurrent+1)
      }).catch(err=>{})
    } else {
        if (TextEditor === '' || TextEditor.trim()==="<p></p>") {
          message.error('新闻内容不能为空！')
        } else {
          setnumCurrent(numCurrent+1) 
        }
    }
  }
  const PreStep = () => {
    setnumCurrent(numCurrent-1)
  }
  const keepDraft = (num) => {
    let http,pathUrl
    const User = JSON.parse(localStorage.getItem('token'))
    if (props.match.params.id) {
      http = axios.patch
      pathUrl=`/news/${props.match.params.id}`
    } else {
       http = axios.post
      pathUrl=`/news`
    }
    http(pathUrl, props.match.params.id ? {
      ...FormConter,
      "content": TextEditor,
       "auditState": num,
    }:{
      ...FormConter,
      "content": TextEditor,
      "region": User.region?User.region: '全球',
      "author": User.username,
      "roleId": User.roleId,
      "auditState": num,
      "publishState": 0,
      "createTime": Date.now(),
      "star": 0,
      "view": 0,
      // "publishTime": 1615778496314
    }).then(res => {
     let path = num === 0 ? '/news-manage/draft': '/audit-manage/list'
      props.history.push(path)
       notification.info({
        message: `通知`,
        description:`您可以在${num ===0?'草稿箱': '审核列表'}查看`,
        placement:'bottomRight'
      });
    })
  }
  const layout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
  };
  useEffect(() => {
     axios.get("/categories").then(res => {
       setcategoryList(res.data)
    })
    if (props.match.params.id) {
      axios.get(`/news/${props.match.params.id}?_expand=category&_expand=role`).then(res => {
        let { title, categoryId, content } = res.data
        newsForm.current.setFieldsValue({
          title,
          categoryId
        })
        setTextEditor(content)
      })
    }
    
  }, []);
  return (
    <div>
        {
        props.match.params.id ?
          <PageHeader
          onBack={() => window.history.back()}
          className="site-page-header"
          title="编辑新闻"
        /> : <PageHeader
          className="site-page-header"
          title="撰写新闻"
        />
        }
        

      <Steps current={numCurrent}>
        <Step title="基本信息" description="新闻标题，新闻分类" />
        <Step title="新闻内容" description="新闻主题内容" />
        <Step title="新闻提交" description="保存草稿或提交审核" />
      </Steps>
      <div className={numCurrent === 0 ? 'marginTop' : 'showActive'}>
        <Form
          {...layout}
          name="basic"
          ref={newsForm}
        >
          <Form.Item
            label="新闻标题"
            name="title"
            rules={[{ required: true, message: '请输入标题!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="新闻分类"
            name="categoryId"
            rules={[{ required: true, message: '请选择分类!' }]}
          >
            <Select>
              {
                categoryList.map(item => {
                 return <Option  value={item.id} key={item.id}>{item.title}</Option>
                })
              }
            </Select>
          </Form.Item>
        </Form>
      </div>
      <div className={numCurrent === 1 ? 'marginTop' : 'showActive'}>
        <NewsEditor onChangeEditor={(val) => {
          setTextEditor(val)
        }} TextEditor={TextEditor}></NewsEditor>
      </div>
      <div className={numCurrent===2? 'marginTop': 'showActive'}></div>
    
      <div style={{ marginTop: '50px' }}>
        {
          numCurrent == 2 && <span>
            <Button type="primary" onClick={()=>{keepDraft(0)}}>保存草稿</Button>
            <Button onClick={()=>{keepDraft(1)}}>提交审核</Button>
           </span>
        }
        {
          numCurrent < 2 && <Button type="primary" onClick={nextStep}>下一步</Button>
        }
        {
          numCurrent > 0 && <Button onClick={PreStep}>上一步</Button>
        }
      </div>
    </div>
  );
}

export default Newsadd;
